package com.lihang0328.groupmessageangel;

import android.Manifest;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class EnsureSendActivity extends AppCompatActivity {
    private EditText ensureName;
    private EditText ensureText;
    private TextView moneyGuesst;
    private Button ensureSend;
    private List<Map<String,Object>> list;
    private final int REQUEST_CODE_ASK_CALL_SENSMS=10011;
    private String SENT_SMS_ACTION = "SENT_SMS_ACTION";
    private String DELIVERED_SMS_ACTION = "DELIVERED_SMS_ACTION";
    private int str_len = 0;
    private BroadcastReceiver sendMessage = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i("TAG", "lihangsend。。" + intent.getAction() + "---" + getResultCode() + "---" + getResultData());
            //判断短信是否发送成功
            switch (getResultCode()) {
                case Activity.RESULT_OK:
                    Toast.makeText(EnsureSendActivity.this,"短信群发助手群发操作成功",Toast.LENGTH_SHORT).show();
                    Intent intent2 = new Intent();
                    intent2.setClassName("com.android.mms", "com.android.mms.ui.ConversationList");
                    startActivity(intent2);
                    finish();
                    break;
                default:
                    Toast.makeText(EnsureSendActivity.this,"短信群发助手群发操作失败",Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i("TAG", "lihangreceiver。。" + intent.getAction() + "---" + getResultCode() + "---" + getResultData());
            switch (getResultCode()) {
                case Activity.RESULT_OK:
                    //表示对方成功收到短信
                    Toast.makeText(EnsureSendActivity.this,"短信群发助手群发操作成功",Toast.LENGTH_SHORT).show();
                    Intent intent2 = new Intent();
                    intent2.setClassName("com.android.mms", "com.android.mms.ui.ConversationList");
                    startActivity(intent2);
                    finish();
                    break;
                default:
                    Toast.makeText(EnsureSendActivity.this,"短信群发助手群发操作失败",Toast.LENGTH_SHORT).show();
                    break;
            }
        }

    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ensure_send);
        ensureSend();
        IntentFilter filter=new IntentFilter();
        filter.addAction(SENT_SMS_ACTION);
        filter.addAction(DELIVERED_SMS_ACTION);
        this.registerReceiver(receiver, filter);
        this.registerReceiver(sendMessage, filter);
        list=ContextActivity.getChooseNameList();
        ensureName=(EditText)findViewById(R.id.et_ensureName);
        ensureText=(EditText)findViewById(R.id.et_ensureText);
        moneyGuesst=(TextView)findViewById(R.id.tv_sendMoney);
        ensureSend=(Button)findViewById(R.id.ensureSend);
        if(getIntent()!=null) {
            //短信内容发送示例
            String ensure_text=getIntent().getStringExtra("text");
            ensureText.setText((String)list.get(0).get("Name")+"同学,"+ensure_text);
        }
        String ensure_name="";
        for(int i=0;i<list.size();i++) {
            HashMap map=(HashMap) list.get(i);
            String name1=(String)map.get("Name");
            ensure_name=ensure_name+name1+",";
            if(i % 5 == 0 && i != 0) ensure_name=ensure_name+"\n";
        }
        ensureName.setText(ensure_name);
        str_len = calculateLength(ensureText.getText().toString());
        int msmNum = (str_len / 70) + 1;
        double money=msmNum*list.size()*0.1;
        moneyGuesst.setText("PS:本次群发预计花费"+String.format("%.1f", money)+"元");
        ensureSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendSms();
            }
        });

    }

    /**
     * 一个个发送短信
     */
    private void sendSms() {
        System.out.println("lihangsend:");
        for(Map map:list) {
            String phone=(String)map.get("Phone");
            String name=(String)map.get("Name");
            String ensure_text=getIntent().getStringExtra("text");
            String text=name+"同学,"+ensure_text;
            System.out.println(phone + " " + name);
            sendSMS(phone,text);
        }
    }
    /**
     * 调用系统发短信的接口
     * @param phoneNumber 电话号码
     * @param message   短信内容
     */
    private static android.telephony.SmsManager smsManager = null;
    private void sendSMS(String phoneNumber, String message) {
        // 获取短信管理器
        if(smsManager == null) smsManager = android.telephony.SmsManager.getDefault();
        Intent sentIntent = new Intent(SENT_SMS_ACTION);
        PendingIntent sentIn = PendingIntent.getBroadcast(this, 0, sentIntent, 0);//PendingIntent.getActivity(this, 0, new Intent(this, EnsureSendActivity.class), 0);
        Intent deliverIntent = new Intent(DELIVERED_SMS_ACTION);
        PendingIntent deliverPI = PendingIntent.getBroadcast(this, 0, deliverIntent, 0);
        // 拆分短信内容（手机短信长度限制）
        System.out.println("lihangsenlen:"+str_len);
        if(str_len > 70) {
            List<String> divideContents = smsManager.divideMessage(message);
            for (String text : divideContents) {
                smsManager.sendTextMessage(phoneNumber, null, text, sentIn, deliverPI);
            }
        }else {
            smsManager.sendTextMessage(phoneNumber, null, message, sentIn, deliverPI);
        }
    }
    /*
    smsManager.sendTextMessage("150xxxxxxxx", null, text, sentPI, deliverPI);

    */
    /**
     * 统计字数
     * @param etstring
     * @return
     */
    private int calculateLength(String etstring) {
        etstring="李行同学,"+etstring;
        char[] ch = etstring.toCharArray();
        int varlength = 0;
        for (int i = 0; i < ch.length; i++) {
            int ascii = Character.codePointAt(ch, i);
            //ascii一共有128个，占1字节 ;汉字占2字节
            if (ascii >= 0 && ascii <= 128) {
                ++ varlength;
            } else {
                varlength = varlength + 2;
            }
        }
        Log.d("TextChanged", "varlength = " + varlength);
        // varlength = etstring.getBytes(CharSet.forName("GBK")).lenght;// u8中文占3个字节
        return varlength;
    }
    /**
     * 判断发送短信权限是否开启
     */
    private void ensureSend() {
        int checkSendEmailPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS);
        System.out.println("lihangensuresend: " + checkSendEmailPermission);
        if(checkSendEmailPermission != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.SEND_SMS},REQUEST_CODE_ASK_CALL_SENSMS);
        }
    }
    /**
     * 申请权限结果
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        System.out.println("lihangen: " + requestCode);
        switch (requestCode) {
            case REQUEST_CODE_ASK_CALL_SENSMS:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    sendSms();
                } else {
                    Toast.makeText(EnsureSendActivity.this, "群发短信失败，没有发送短信权限授权噢~", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

}
